package com.citywithincity.pay;

import java.io.IOException;
import java.util.Map;

import com.citywithincity.db.Db;

public class PayContext {
	
	public static final PayState NO_PAY_STATE;
	public static final PayState SUBMITING_STATE;
	public static final PayState SUBMIERROR_STATE;
	public static final PayState SUCCESS_STATE;
	
	static{
		NO_PAY_STATE = new NoPayState();
		SUBMITING_STATE = new SubmitingState();
		SUBMIERROR_STATE = new SubmitingErrorState();
		SUCCESS_STATE = new SuccessState();
	}
	
	public static interface PayState{
		void handle(PayContext context);
	}
	
	public static class SuccessState implements PayState{

		@Override
		public void handle(PayContext context) {
			//状态变成成功
			if(context.order.getPayStatus() != OrderStatus.OrderStatus_Success){
				//
				context.onSuccess();
			}
		}
		
	}
	
	public static class SubmitingErrorState implements PayState{

		@Override
		public void handle(PayContext context) {
			//状态变成error
			if(context.order.getPayStatus() != OrderStatus.OrderStatus_SubmitError){
				//
				//这里更新状态
				
			}
		}
		
	}
	
	public static class NoPayState implements PayState{

		@Override
		public void handle(PayContext context) {
			if(Db.ar().where("","").update("")>0){
				context.setState(SUBMITING_STATE);
				context.handle();
			}
		}
	}

	public static class SubmitingState implements PayState{

		@Override
		public void handle(PayContext context) {
			int sendTimes = 0;
			//这里进行提交任务
			while(true){
				try {
					 Map<String, Object> data = context.submit();
					 context.setSubmitResult(data);
					 context.setState(SUCCESS_STATE);
				} catch (IOException e) {
					//这里可以再次发送
					if(++sendTimes > context.getRetryTimes()){
						context.setState(SUBMIERROR_STATE);
						break;
					}
				}catch (Throwable e) {
					context.setState(SUBMIERROR_STATE);
				}
			}
			context.handle();
		}
	}
	
	private SysOrder order;
	private PayState state;
	
	public PayContext(SysOrder order){
		this.state = createState(order.getPayStatus());
		this.order = order;
	}
	
	public int getRetryTimes() {
		// TODO Auto-generated method stub
		return 0;
	}

	public void onSuccess() {
		
	}

	public void setSubmitResult(Map<String, Object> data) {
		
	}

	/**
	 * 提交任务
	 * @return
	 * @throws Exception
	 */
	public Map<String, Object> submit() throws IOException {
		// TODO Auto-generated method stub
		
		return null;
	}

	private PayState createState(int state){
		
		return null;
	}
	
	
	public void setState(PayState state){
		this.state = state;
	}
	

	
	public void handle(){
		this.state.handle(this);
	}
	
	
}
